#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# -= project0/at_ccs.py coding by Scott in 2019-06-05 16:58 with IDE:PyCharm =-
import json
import requests
from redis import StrictRedis
from config.constants import *
from config import Cfg


def get_access_token(appid):
    try:
        # redis_connection0 = StrictRedis(host=Cfg.redis_host, port=6379, db=0, decode_responses=True)
        redis_connection1 = StrictRedis(host=Cfg.redis_host, port=6379, db=1, decode_responses=True)
    except Exception as e:
        # 日志记录appid及错误信息
        return None

    access_token = redis_connection1.get(appid)

    if not access_token:
        # secret = redis_connection0.get(appid)
        secret = Cfg.secret
        rp = requests.get(get_access_token_url.format(appid, secret))
        rp_data = json.loads(rp.text)
        if rp_data.get('errcode'):
            # 日志记录错误码及错误信息
            pass
        redis_connection1.set(appid, rp_data['access_token'], 7000)
        return rp_data['access_token']

    return access_token
